package com.example.demo.mapper;

import com.mybatisflex.core.BaseMapper;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.example.demo.entity.User;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

import static com.example.demo.entity.table.UserTableDef.USER;
import static com.example.demo.entity.table.DepartmentTableDef.DEPARTMENT;

/**
 * 用户Mapper接口
 */
@Mapper
public interface UserMapper extends BaseMapper<User> {

    /**
     * 根据部门名称查询用户
     */
    default List<User> selectUsersByDepartment(String deptName) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(USER.ID, USER.NAME, DEPARTMENT.NAME.as("deptName"))
                .from(USER)
                .innerJoin(DEPARTMENT).as("d").on(USER.DEPT_ID.eq(DEPARTMENT.ID))
                .where(DEPARTMENT.NAME.like(deptName + "%"));

        return selectListByQuery(queryWrapper);
    }

    /**
     * 分页查询用户
     */
    default Page<User> paginateUser(int pageNumber, int pageSize, String searchName) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .where(USER.NAME.like("%" + searchName + "%"))
                .and(USER.IS_DELETED.eq(false))
                .orderBy(USER.ID.desc());

        return paginate(pageNumber, pageSize, queryWrapper);
    }

    /**
     * 查询用户及其账户信息
     */
    default List<User> selectUsersWithAccount() {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(USER.ALL_COLUMNS)
                .from(USER)
                .leftJoin("tb_account").as("a").on(USER.ID.eq("a.user_id"));

        return selectListByQuery(queryWrapper);
    }
}